package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Component
public class AccessFilter extends ZuulFilter {
    //过滤器类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    //过滤器的顺序号
    @Override
    public int filterOrder() {
        //有五个默认过滤器,自己的过滤器加到末尾
        return 6;
    }
    //针对当前请求,判断是否要执行过滤代码
    @Override
    public boolean shouldFilter() {
        //先获得当前请求的上下文对象
        RequestContext ctx 
                = RequestContext.getCurrentContext();
        //当前请求,调用的的服务id
        String serviceId =
                (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        //调用的是否是item-service
        return "item-service".equals(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //获得上下文对象
        RequestContext ctx
                = RequestContext.getCurrentContext();
        //获得request对象
        HttpServletRequest request = ctx.getRequest();
        //接受token参数
        String token = request.getParameter("token");
        //如果没有token阻止继续调用,直接返回响应
        if (StringUtils.isBlank(token)){
            ctx.setSendZuulResponse(false);
            ctx.addZuulRequestHeader("Content-Type"
                    , "application/json;charset=UTF-8");
            ctx.setResponseBody(JsonResult
                    .err()
                    .code(400)
                    .msg("Not login 未登录")
                    .toString());
        }
        return null;
    }
}
